package com.ruoyi.web.controller.merchant;

import com.ruoyi.basedata.domain.Bank;
import com.ruoyi.basedata.domain.WalletKind;
import com.ruoyi.basedata.service.IBankService;
import com.ruoyi.basedata.service.IWalletKindService;
import com.ruoyi.channel.domain.ChannelWallet;
import com.ruoyi.channel.service.IChannelWalletService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.GoogleCodeUtil;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.common.utils.SignUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.financial.domain.MpFinancialSetting;
import com.ruoyi.financial.service.IMpFinancialSettingService;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.service.IMpMerchantService;
import com.ruoyi.merchant.service.IMpMerchantWalletService;
import com.ruoyi.withdrawalParam.domain.WithdrawalReq;
import com.ruoyi.withdrawalParam.domain.WithdrawalRsp;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 *  信息操作处理
 *
 * @author ruoyi
 * @date 2019-05-06
 */
@Controller
@RequestMapping("/merchant/wallet")
public class MpMerchantWalletController extends BaseController
{
	Logger log = LoggerFactory.getLogger(MpMerchantWalletController.class);
	private String prefix = "merchant/mpMerchantWallet";
	public final static String SUCCESS = "success";

	@Autowired
	private IMpMerchantWalletService mpMerchantWalletService;
	@Autowired
	private IChannelWalletService channelWalletService;
	@Autowired
	private IMpFinancialSettingService financialSettingService;
	@Autowired
	private IBankService bankService;
	@Autowired
	private IMpMerchantService merchantService;
	@Autowired
	private IWalletKindService walletKindService;

	// 商户管理-商户钱包  申请代付接口地址-外部
	@Value("${reqUrlConfig.merchantWithdrawal}")
	private String merchantWithdrawal;

	@RequiresPermissions("merchant:mpMerchantWallet:view")
	@GetMapping()
	public String mpMerchantWallet()
	{
		return prefix + "/mpMerchantWallet";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("merchant:mpMerchantWallet:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(MpMerchantWallet mpMerchantWallet, String channelName)
	{
		startPage();
		List<MpMerchantWalletVo> list = mpMerchantWalletService.selectMpMerchantWalletList(mpMerchantWallet);
		return getDataTable(list);
	}


	/**
	 * 导出列表
	 */
	@RequiresPermissions("merchant:mpMerchantWallet:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(MpMerchantWallet mpMerchantWallet)
	{
		List<MpMerchantWalletVo> list = mpMerchantWalletService.selectMpMerchantWalletList(mpMerchantWallet);
		ExcelUtil<MpMerchantWalletVo> util = new ExcelUtil<MpMerchantWalletVo>(MpMerchantWalletVo.class);
		return util.exportExcel(list, "mpMerchantWallet");
	}

	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add()
	{
		return prefix + "/add";
	}

	/**
	 * 新增保存
	 */
	@RequiresPermissions("merchant:mpMerchantWallet:add")
	@Log(title = "商户钱包", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(MpMerchantWallet mpMerchantWallet)
	{
		MpMerchantWallet mpMerchantWallet1 = mpMerchantWalletService.checkMerchantWallet(mpMerchantWallet);
		if(mpMerchantWallet1 == null) {
			return toAjax(mpMerchantWalletService.insertMpMerchantWallet(mpMerchantWallet));
		}else{
			return new AjaxResult(AjaxResult.Type.ERROR,"该商户钱包已存在");
		}
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		MpMerchantWalletVo mpMerchantWalletVo = mpMerchantWalletService.selectMpMerchantWalletVoById(id);
		mmap.put("mpMerchantWallet", mpMerchantWalletVo);
		return prefix + "/edit";
	}

	/**
	 * 修改保存
	 */
	@RequiresPermissions("merchant:mpMerchantWallet:edit")
	@Log(title = "商户钱包", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(MpMerchantWallet mpMerchantWallet)
	{
		return toAjax(mpMerchantWalletService.updateMpMerchantWallet(mpMerchantWallet));
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("merchant:mpMerchantWallet:remove")
	@Log(title = "商户钱包", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{
		return toAjax(mpMerchantWalletService.deleteMpMerchantWalletByIds(ids));
	}


	/**
	 * 商户代付
	 */
	@GetMapping("/withdrawal")
	public String withdrawal() {
		return prefix + "/merchantWithdrawal";
	}


	/**
	 * 渠道钱包列表
	 */
	@PostMapping("/channelWallet")
	@ResponseBody
	public TableDataInfo channelWalletList(int status) {
		startPage();
		List<MerchantWithdrawal> list = mpMerchantWalletService.channelWalletList(status);
		return getDataTable(list);
	}



	/**
	 * 渠道钱包信息
	 */
	@PostMapping("/channelWalletInfo")
	@ResponseBody
	public TableDataInfo channelWalletInfo (Long channelMethodId) {
		startPage();
		List<ChannelWallet> list  = channelWalletService.selectChannelWalletByChannelMethodId(channelMethodId);
		return getDataTable(list);
	}


	/**
	 * 商户代付
	 */
	@PostMapping("/withdrawalPay")
	@ResponseBody
	public AjaxResult withdrawalPay(MerchantWithdrawalPay merchantWithdrawalPay) {
		try{
			MpFinancialSetting setting = new MpFinancialSetting();
			List<MpFinancialSetting> mpFinancialSettings = financialSettingService.selectMpFinancialSettingList(setting);
			MpFinancialSetting mpFinancialSetting = mpFinancialSettings.get(0);
			if (StringUtils.isNotNull(mpFinancialSetting)) {
				// 取款密码
				boolean password = merchantWithdrawalPay.getWithdrawalPassword().equals(mpFinancialSetting.getWithdrawalPassword());
				// 谷歌验证
				boolean googleCode = GoogleCodeUtil.ValidCode(merchantWithdrawalPay.getGoogleCode(), mpFinancialSetting.getGoogleSecret());
				if (!password) {
					return AjaxResult.error("取款密码错误！");
				}
				if (!googleCode) {
					return AjaxResult.error("验证码验证失败！");
				}
				if (password && googleCode) {
					// 封装请求参数
					WithdrawalReq withdrawalReq = makeReqParams(merchantWithdrawalPay);
					log.info("请求的报文" + withdrawalReq.alltoString());
					String result = HttpUtils.sendPost(merchantWithdrawal, withdrawalReq.alltoString(), false);
					if (StringUtils.isNotEmpty(result)) {
						JSONObject jsonObjectResult = JSONObject.fromObject(result);
						WithdrawalRsp withdrawalRsp = (WithdrawalRsp) net.sf.json.JSONObject.toBean(jsonObjectResult, WithdrawalRsp.class);
						if (SUCCESS.equals(withdrawalRsp.getCode())) {
							return AjaxResult.success(withdrawalRsp.getMsg());
						}else {
							return AjaxResult.error(withdrawalRsp.getMsg());
						}
					}else {
						return AjaxResult.error("请求失败!");
					}
				}
			}
			return AjaxResult.error("没有进行账户相关设置");
		}catch (Exception e){
			e.printStackTrace();
			return AjaxResult.error("系统异常");
		}
	}




	/**
	 * 封装代付请求参数
	 */
	public WithdrawalReq makeReqParams(MerchantWithdrawalPay merchantWithdrawalPay){
		// 查询银行
		Bank bank = bankService.selectBankById(merchantWithdrawalPay.getBankId().intValue());
		WithdrawalReq withdrawal = new WithdrawalReq();
		// 商户号
		MpMerchant merchant = merchantService.selectMpMerchantById(merchantWithdrawalPay.getMerchantId());
		withdrawal.setMch_id(merchant.getCode());
		// 商户订单号
		String orderNumber = OrderUtils.createOrderCode(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
		withdrawal.setOut_trade_no(orderNumber);
		// 金额
		withdrawal.setTotal_fee(merchantWithdrawalPay.getAccountBalance());
		// 持卡人名称
		withdrawal.setBank_car_name(merchantWithdrawalPay.getBankAccountOwner());
		// 银行卡账户
		withdrawal.setBank_car_no(merchantWithdrawalPay.getBankAccountNo());
		// 开户银行代码
		withdrawal.setBank_type(bank.getCode());
		// 开户分行
		withdrawal.setBank_address(merchantWithdrawalPay.getBankBranch());
		// 支行名称
		withdrawal.setBranch(merchantWithdrawalPay.getBankSubBranch());
		// 开户省
		withdrawal.setBank_province(merchantWithdrawalPay.getBankProvince());
		// 开户市
		withdrawal.setBank_city(merchantWithdrawalPay.getBankCity());
		// 联行号
		if (StringUtils.isNotBlank(merchantWithdrawalPay.getBankUnionNo())) {
			withdrawal.setUnionBankNum(merchantWithdrawalPay.getBankUnionNo());
		}
		// 钱包类型
		WalletKind walletKind = walletKindService.selectWalletKindById(merchantWithdrawalPay.getWalletKindId().intValue());
		withdrawal.setWallet_type(walletKind.getCode());
		// 获取 sign
		String preString = withdrawal.toStringOther();
		String key = merchant.getSecretKey();
		String sign = SignUtil.getSignReq(preString, key);
		withdrawal.setSign(sign);
		return withdrawal;
	}
}
